import cv2 as cv
import numpy as np
import math
# from find_square import Reference_point_x,Reference_point_y
import find_square
import Rotated_L45_find_square


def detect_circles(gray_frame):
    # 使用霍夫圆变换检测圆形
    circles = cv.HoughCircles(gray_frame, cv.HOUGH_GRADIENT, dp=1, minDist=60,
                               param1=200, param2=28, minRadius=10, maxRadius=100)
    if circles is not None:
        circles = np.round(circles[0, :]).astype("int")
        return circles
    return np.array([])

#过滤面积
def filter_circles(circles, min_area,max_area):
    filtered_circles = []
    for (x, y, r) in circles:
        area = math.pi * (r ** 2)
        # print("area is",area)
        if max_area >area > min_area:
            filtered_circles.append((x, y, r))
    return np.array(filtered_circles)


def is_pure_color(circle_roi, color_tolerance):
    # 将圆形区域转换为 numpy 数组
    circle_roi = np.array(circle_roi)

    # 计算圆形区域的颜色均值和方差
    mean_color = np.mean(circle_roi, axis=(0, 1))
    stddev_color = np.std(circle_roi, axis=(0, 1))
    print(stddev_color)
    # 判断方差是否小于容忍度
    return np.all(stddev_color < color_tolerance)

white_circles_transformed_points = []
black_circles_transformed_points = []
def circles_detect(img,dirction):
    global white_circles_transformed_points
    global black_circles_transformed_points

    min_area = 1500  # 过滤圆形的最小面积
    max_area = 7000
    color_tolerance =70   # 颜色方差容忍度，

    # 转换为灰度图像
    gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)


    # 应用中值滤波以进一步减少噪声
    median_filtered = cv.medianBlur(gray, 5)

    # Canny 边缘检测
    edged = cv.Canny(median_filtered, 50, 50)

    # 识别圆形
    circles = detect_circles(median_filtered)

    # 过滤不符合条件的圆形
    filtered_circles = filter_circles(circles, min_area, max_area)

    white_circles_center_and_radius = []
    black_circles_center_and_radius = []
    if filtered_circles.size > 0:
        for (x, y, r) in filtered_circles:
            # 提取圆形区域
            circle_roi = img[y - r:y + r, x - r:x + r]
            # if circle_roi.size > 0:
            if circle_roi.size > 0 and is_pure_color(circle_roi, color_tolerance):
                # 计算圆形区域的平均颜色
                avg_color = cv.mean(circle_roi)[:3]
                avg_gray = np.mean(avg_color)
                # print("avg_gray",avg_gray)

                # 判断颜色类型
                color_name = None
                if avg_gray > 200:  # 近似白色
                    circle_color = (255, 255, 255)
                    color_name = "white"
                else:
                    circle_color = (0, 0, 0)
                    color_name = "black"

                # 打印圆的面积
                # area = math.pi * (r ** 2)
                # print(f"Detected {color_name} circle at (x={x}, y={y}) with radius={r} and area={area:.2f}")

                # 绘制圆形和圆心
                cv.circle(img, (x, y), r, circle_color, 2)
                cv.rectangle(img, (x - 2, y - 2), (x + 2, y + 2), (0, 0, 255), -1)
                if color_name is None:
                    return
                elif color_name is "white":
                    white_circles_center_and_radius.append([x,y,r])
                elif color_name is "black":
                    black_circles_center_and_radius.append([x,y,r])

        # if reference_point_choose == "0":
        # 白色棋子坐标转换到参考坐标系
        if dirction == "forward":
            white_circles_transformed_points = []
            for (x, y, r) in white_circles_center_and_radius:
                transformed_x = x - find_square.Reference_point_x
                transformed_y = -(y - find_square.Reference_point_y)  # 取负号操作
                white_circles_transformed_points.append((transformed_x, transformed_y))
            # 黑色棋子坐标转换到参考坐标系
            black_circles_transformed_points = []
            for (x, y, r) in black_circles_center_and_radius:
                transformed_x = x - find_square.Reference_point_x
                transformed_y = -(y - find_square.Reference_point_y)  # 取负号操作
                black_circles_transformed_points.append((transformed_x, transformed_y))

        if dirction == "L45":
            white_circles_transformed_points = []
            for (x, y, r) in white_circles_center_and_radius:
                transformed_x = x - Rotated_L45_find_square.L45_Reference_point_x
                transformed_y = -(y - Rotated_L45_find_square.L45_Reference_point_y)  # 取负号操作
                white_circles_transformed_points.append((transformed_x, transformed_y))
            # 黑色棋子坐标转换到参考坐标系
            black_circles_transformed_points = []
            for (x, y, r) in black_circles_center_and_radius:
                transformed_x = x - Rotated_L45_find_square.L45_Reference_point_x
                transformed_y = -(y - Rotated_L45_find_square.L45_Reference_point_y)  # 取负号操作
                black_circles_transformed_points.append((transformed_x, transformed_y))


        # elif reference_point_choose == "L45":
        #     # 白色棋子坐标转换到参考坐标系
        #     white_circles_transformed_points = []
        #     for (x, y, r) in white_circles_center_and_radius:
        #         transformed_x = x - Rotated_L45_find_square.Rotated_L45_Reference_point_x
        #         transformed_y = -(y - Rotated_L45_find_square.Rotated_L45_Reference_point_y)  # 取负号操作
        #         white_circles_transformed_points.append((transformed_x, transformed_y))
        #     # 黑色棋子坐标转换到参考坐标系
        #     black_circles_transformed_points = []
        #     for (x, y, r) in black_circles_center_and_radius:
        #         transformed_x = x - Rotated_L45_find_square.Rotated_L45_Reference_point_x
        #         transformed_y = -(y - Rotated_L45_find_square.Rotated_L45_Reference_point_y)  # 取负号操作
        #         black_circles_transformed_points.append((transformed_x, transformed_y))
    # 显示处理后的图像
    # cv.imshow("Detected Circles", img)

    return img
